<template>
  <div>
    <div class="header">
      <span style="margin-left: 10px; text-align: right">关键字</span>
      <el-input
        placeholder="请输入关键字"
        v-model="req.keyword"
        style="width: 200px; margin-left: 10px"
      ></el-input>
      <span style="margin-left: 10px; text-align: right">案件号</span>
      <el-input
        placeholder="请输入案件流水号"
        v-model="req.caseNo"
        style="width: 160px; margin-left: 10px"
      ></el-input>
      <span style="text-align: right; margin-left: 10px">开票日期</span>
      <el-date-picker
        v-model="req.dealDates"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        style="margin-left: 10px"
      ></el-date-picker>
      <span style="text-align: right; margin-left: 10px">录入日期</span>
      <el-date-picker
        v-model="req.createDates"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :picker-options="pickerOptions"
        style="margin-left: 10px"
      ></el-date-picker>

      <el-button
        plain
        type="primary"
        style="margin-left: 34px"
        icon="el-icon-search"
        @click="getInvoices()"
      >
        搜索
      </el-button>
      <el-button
        type="success"
        style="margin-left: 10px"
        icon="el-icon-plus"
        @click="
          curInvoice = { IN_EmpID: curInvoice ? curInvoice.IN_EmpID : null }
          addInvoiceVis = true
        "
      >
        票据录入
      </el-button>
      <el-button
        plain
        type="primary"
        style="margin-left: 10px"
        size="small"
        @click="outputExcel"
      >
        导出报表
      </el-button>
    </div>
    <div class="main">
      <el-table
        style="overflow: auto"
        height="100%"
        :data="res.Items"
        stripe
        border
        highlight-current-row
      >
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column label="发票号码" width="120">
          <template slot-scope="scope">
            <el-popover
              placement="top-start"
              trigger="hover"
              v-if="scope.row.IN_No"
            >
              <div>[{{ scope.row.IN_ID }}]{{ scope.row.IN_No }}</div>
              <p slot="reference">
                {{
                  scope.row.IN_No.length > 10
                    ? scope.row.IN_No.substring(0, 10) + '...'
                    : scope.row.IN_No
                }}
              </p>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="发票金额" width="160">
          <template slot-scope="scope">
            <el-tag :type="scope.row.IN_Status == 100 ? 'success' : 'primary'">
              {{ scope.row.StatusDesc }}
            </el-tag>
            {{ scope.row.IN_Fee }}元
            <!-- <span v-if="scope.row.IN_Fee">价税合计:{{ scope.row.IN_Fee }}</span>
            <span v-if="scope.row.IN_TaxFee" style="margin-left: 10px">
              税额:{{ scope.row.IN_TaxFee }}
            </span>
            <span v-if="scope.row.IN_FeeWithoutTax" style="margin-left: 10px">
              金额:{{ scope.row.IN_FeeWithoutTax }}
            </span> -->
          </template>
        </el-table-column>
        <el-table-column label="实际发生日期" width="100">
          <template slot-scope="scope">
            {{ scope.row.IN_UsedDate | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="报销性质" width="80">
          <template slot-scope="scope">
            {{ scope.row.INTY_EnumTxt }}
          </template>
        </el-table-column>
        <el-table-column label="报销人" width="80">
          <template slot-scope="scope">
            {{ scope.row.USR_Name }}
          </template>
        </el-table-column>
        <el-table-column label="报销地址" width="160">
          <template slot-scope="scope">
            {{ scope.row.IN_AreaDesc }}
          </template>
        </el-table-column>
        <el-table-column label="报销案件" width="200">
          <template slot-scope="scope">
            <div
              v-for="expCase in scope.row.ExpenseCases"
              :key="expCase.CEX_ID"
            >
              <el-link
                slot="reference"
                style="color: blue"
                @click="toForm(expCase.CEX_FormID)"
              >
                {{ expCase.CS_No }}
                <span v-if="expCase.FRS_Name">[{{ expCase.FRS_Name }}]</span>
              </el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="抬头" width="260">
          <template slot-scope="scope">
            {{ scope.row.IN_Title }}
            <!-- <el-popover
              placement="top-start"
              trigger="hover"
              v-if="scope.row.IN_Title"
            >
              <div>{{ scope.row.IN_Title }}</div>
              <p slot="reference">
                {{
                  scope.row.IN_Title.length > 11
                    ? scope.row.IN_Title.substring(0, 11) + '...'
                    : scope.row.IN_Title
                }}
              </p>
            </el-popover> -->
          </template>
        </el-table-column>
        <el-table-column label="备注">
          <template slot-scope="scope">
            {{ scope.row.IN_Remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              icon="el-icon-picture"
              @click="
                curInvoice = scope.row
                imageVis = true
              "
            ></el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="
                curInvoice = scope.row
                editInvoiceVis = true
              "
            ></el-button>
            <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="deleteInvoice(scope.row.IN_ID)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      layout="total,prev,pager,next,sizes"
      style="float: right"
      background
      :current-page.sync="req.pageIndex"
      :page-size="req.pageSize"
      :total="res.Total"
      :page-sizes="[12, 18]"
      @size-change="
        (val) => {
          req.pageSize = val
          getInvoices()
        }
      "
      @current-change="getInvoices()"
    ></el-pagination>

    <el-drawer
      title="差旅费录入"
      :visible.sync="addInvoiceVis"
      :with-header="false"
      direction="rtl"
      size="520px"
    >
      <el-form
        v-if="curInvoice"
        label-width="100px"
        label-position="left"
        style="
          margin-left: 20px;
          margin-top: 20px;
          overflow: auto;
          height: 100vh;
        "
      >
        <el-form-item label="扫描件">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="fileUploadUrl"
            :show-file-list="false"
            :on-progress="onProgress"
            :on-error="uploadErr"
            :on-success="uploadSuccess"
            :headers="myHeaders"
          >
            <el-image
              class="avatar"
              fit="fill"
              v-if="curInvoice.FL_SrcPath"
              :src="fileURL + curInvoice.FL_SrcPath"
            ></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-progress
            v-if="uploadPercentage"
            :percentage="uploadPercentage"
          ></el-progress>
        </el-form-item>
        <el-form-item v-if="ticketFile">
          <ticketIdentify :file="ticketFile" @output="ticketAIOutput" />
        </el-form-item>
        <el-form-item label="报销人员">
          <el-select
            filterable
            v-model="curInvoice.IN_EmpID"
            style="width: 300px"
          >
            <el-option
              v-for="(item, index) in employees"
              :key="index"
              :label="item.USR_Name"
              :value="item.ECV_TargetID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销性质">
          <el-select
            filterable
            v-model="curInvoice.IN_Type"
            style="width: 300px"
          >
            <el-option
              v-for="(item, index) in invoiceTypes"
              :key="index"
              :label="item.INTY_EnumTxt"
              :value="item.INTY_ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销地址">
          <el-cascader
            style="width: 300px"
            :options="chinaAreaData"
            @change="areaChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model="curInvoice.IN_No" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="抬头">
          <el-input
            v-model="curInvoice.IN_Title"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item label="价税合计">
          <el-input v-model="curInvoice.IN_Fee" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="税额">
          <el-input
            v-model="curInvoice.IN_TaxFee"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="金额">
          <el-input
            v-model="curInvoice.IN_FeeWithoutTax"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            align="right"
            v-model="curInvoice.IN_DealDate"
            placeholder="请选择开票日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            style="width: 300px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="实际发生时间">
          <el-date-picker
            align="right"
            v-model="curInvoice.IN_UsedDate"
            placeholder="请选择实际发生时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            style="width: 300px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="curInvoice.IN_Remark"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addInvoice()">录入</el-button>
          <el-button type="text" @click="addInvoiceVis = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer
      title="信息修改"
      :visible.sync="editInvoiceVis"
      :with-header="false"
      direction="rtl"
      size="480px"
    >
      <el-form
        v-if="curInvoice"
        label-width="100px"
        label-position="left"
        style="
          margin-left: 20px;
          margin-top: 20px;
          overflow: auto;
          height: 100vh;
        "
      >
        <el-form-item label="扫描件">
          <el-upload
            class="avatar-uploader"
            :action="fileUploadUrl"
            :show-file-list="false"
            :on-progress="onProgress"
            :on-error="uploadErr"
            :on-success="uploadSuccess"
            :headers="myHeaders"
          >
            <el-image
              class="avatar"
              fit="fill"
              v-if="curInvoice.FL_SrcPath"
              :src="fileURL + curInvoice.FL_SrcPath"
            ></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-progress
            v-if="uploadPercentage"
            :percentage="uploadPercentage"
          ></el-progress>
        </el-form-item>
        <el-form-item label="报销人员">
          <el-select
            filterable
            v-model="curInvoice.IN_EmpID"
            style="width: 300px"
          >
            <el-option
              v-for="(item, index) in employees"
              :key="index"
              :label="item.USR_Name"
              :value="item.ECV_TargetID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销性质">
          <el-select
            filterable
            v-model="curInvoice.IN_Type"
            style="width: 300px"
          >
            <el-option
              v-for="(item, index) in invoiceTypes"
              :key="index"
              :label="item.INTY_EnumTxt"
              :value="item.INTY_ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报销地址">
          <el-cascader
            style="width: 300px"
            :options="chinaAreaData"
            :value="areaConvert(curInvoice.IN_Area)"
            @change="areaChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="编号">
          <el-input v-model="curInvoice.IN_No" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="抬头">
          <el-input
            v-model="curInvoice.IN_Title"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item label="价税合计">
          <el-input v-model="curInvoice.IN_Fee" style="width: 300px"></el-input>
        </el-form-item>
        <el-form-item label="税额">
          <el-input
            v-model="curInvoice.IN_TaxFee"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="金额">
          <el-input
            v-model="curInvoice.IN_FeeWithoutTax"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            align="right"
            v-model="curInvoice.IN_DealDate"
            placeholder="请选择开票日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            style="width: 300px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="实际发生时间">
          <el-date-picker
            align="right"
            v-model="curInvoice.IN_UsedDate"
            placeholder="请选择实际发生时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="date"
            style="width: 300px"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="curInvoice.IN_Remark"
            style="width: 300px"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="warning" @click="editInvoice()">保存</el-button>
          <el-button type="text" @click="editInvoiceVis = false">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- <el-dialog :visible.sync="imageVis" :modal-append-to-body="false" center>
      <el-image
        v-if="curInvoice && curInvoice.FL_SrcPath"
        :src="fileURL + curInvoice.FL_SrcPath"
        fit="fill"
        :preview-src-list="[fileURL + curInvoice.FL_SrcPath]"
      ></el-image>
      <div v-else>未上传发票</div>
    </el-dialog> -->
    <el-image-viewer
      v-if="imageVis"
      :url-list="[fileURL + curInvoice.FL_SrcPath]"
      :on-close="closeImage"
    ></el-image-viewer>
  </div>
</template>
<script>
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
import {
  getInvoiceTypes,
  getEmployees,
  getInvoices,
  addInvoice,
  editInvoice,
  deleteInvoice,
} from '@/api/core/invoice'
import {
  baseURL,
  fileRoot,
  fileUploadRoot,
  empIdName,
  tokenName,
} from '@/config'
import axios from 'axios'
import ticketIdentify from './components/ticketIdentify.vue'
import { provinceAndCityDataPlus, CodeToText } from 'element-china-area-data'
export default {
  components: { ticketIdentify, elImageViewer },
  data: function () {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            },
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            },
          },
        ],
      },
      req: {
        keyword: null,
        dealDates: [],
        createDates: [],
        pageIndex: 1,
        pageSize: 12,
      },
      res: {
        Items: [],
        Total: 0,
      },
      curInvoice: null,
      invoiceTypes: [],
      employees: [],

      chinaAreaData: provinceAndCityDataPlus,
      fileURL: baseURL + fileRoot,
      fileUploadUrl: baseURL + fileUploadRoot,
      uploadPercentage: 0,
      addInvoiceVis: false,
      editInvoiceVis: false,
      myHeaders: {},

      ticketFile: null,
      imageVis: false,
    }
  },
  methods: {
    toForm(formId) {
      this.$router.push({
        name: 'formInfoPage',
        query: { formId },
      })
    },
    closeImage() {
      this.imageVis = false
      return true
    },
    ticketAIOutput(val) {
      // this.curInvoice.IN_DealDate = val.dealdate
      // this.curInvoice.IN_No = val.invNo
      // this.curInvoice.IN_Fee = val.fee
      // this.curInvoice.IN_TaxFee = val.taxFee
      // this.curInvoice.IN_FeeWithoutTax = val.feeWithoutTax
      this.$set(this.curInvoice, 'IN_DealDate', val.dealdate)
      this.$set(this.curInvoice, 'IN_No', val.invNo)
      this.$set(this.curInvoice, 'IN_Fee', val.fee)
      this.$set(this.curInvoice, 'IN_TaxFee', val.taxFee)
      this.$set(this.curInvoice, 'IN_FeeWithoutTax', val.feeWithoutTax)
      this.$set(this.curInvoice, 'IN_Title', val.title)
      // console.log(val)

      this.$forceUpdate()
    },
    areaConvert(areas) {
      if (areas) return JSON.parse(areas)
    },
    areaChange(val) {
      this.curInvoice.IN_Area = JSON.stringify(val)
      this.curInvoice.IN_AreaDesc = ''
      val?.forEach((x) => {
        this.curInvoice.IN_AreaDesc += CodeToText[x]
      })
      console.log(this.curInvoice.IN_AreaDesc)
    },
    uploadSuccess(res) {
      if (res.success) {
        let file = res.data
        this.$set(this.curInvoice, 'FL_Name', file.FL_Name)
        this.$set(this.curInvoice, 'FL_SrcPath', file.FL_SrcPath)
        this.$set(this.curInvoice, 'IN_FileID', file.FL_ID)
        this.uploadPercentage = 0
        this.ticketFile = this.$refs.upload.uploadFiles.pop().raw
      } else {
        alert(res.errormsg)
      }
    },
    uploadErr(err) {
      alert(JSON.stringify(err))
    },
    onProgress(event) {
      this.uploadPercentage = Math.round(event.percent * 100) / 100
    },
    addInvoice() {
      addInvoice(this.curInvoice).then(() => {
        this.getInvoices()
        this.addInvoiceVis = false
      })
    },
    editInvoice() {
      editInvoice(this.curInvoice).then(() => {
        this.getInvoices()
        this.editInvoiceVis = false
      })
    },
    getInvoiceTypes: function () {
      getInvoiceTypes().then(({ data }) => {
        this.invoiceTypes = data
      })
    },
    getEmployees: function () {
      getEmployees().then(({ data }) => {
        this.employees = data
      })
    },
    getInvoices: function () {
      getInvoices(this.req).then(({ data }) => {
        this.res = data
      })
    },
    deleteInvoice(id) {
      this.$confirm(`是否删除该票据`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteInvoice(id).then(() => {
          this.getInvoices()
        })
      })
    },
    outputExcel() {
      if (
        !this.req.keyword &&
        this.req.createDates.length == 0 &&
        this.req.dealDates.length == 0
      ) {
        this.$message('请选择导出信息（关键字/开票日期/录入日期）')
        return
      }
      var config = {
        baseURL,
        headers: {},
        responseType: 'blob',
      }
      config.headers[tokenName] = this.$store.getters['user/accessToken']
      config.headers[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
      axios
        .post('/api/Case/Invoice/OutputInvoiceExcel', this.req, config)
        .then((response) => {
          var blob = new Blob([response.data])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '差旅费报表.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch((error) => {
          console.log('response: ', error)
        })
    },
  },
  created: function () {
    var data = this.$store.getters['pagination/getRoutePage'](this.$route)
    Object.assign(this.$data, data)
    this.myHeaders[tokenName] = this.$store.getters['user/accessToken']
    this.myHeaders[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
    this.getInvoices()
    this.getEmployees()
    this.getInvoiceTypes()
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('pagination/setRoutePage', {
      route: this.$route,
      pageData: this.$data,
    })
    next()
  },
}
</script>
<style scoped>
.header {
  width: 100%;
  padding-top: 10px;
  padding-bottom: 10px;
  height: auto;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  background: #ffffff;
  border-radius: 5px;
  border-bottom: #f4f8ff 2px solid;
  display: flex;
  margin-bottom: 11px;
  align-items: center;
}
.main {
  height: calc(100% - 160px);
}
.dialogLabel {
  margin-left: 10px;
  width: 100px;
  text-align: right;
  display: inline-block;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 220px;
  line-height: 220px;
  text-align: center;
  border-style: dashed;
  border-width: thin;
}
.avatar {
  width: 300px;
  height: 220px;
  display: block;
  border-style: dashed;
  border-width: thin;
}
</style>

<style>
.el-table .warning-row {
  background-color: oldlace;
}
</style>
